package com.xcm.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xcm.cache.RedisCacheDao;
import com.xcm.config.CustomProperties;
import com.xcm.constant.BusinessConstant;
import com.xcm.constant.ResponseConstant;
import com.xcm.exception.ControllerException;
import com.xcm.exception.ServiceException;
import com.xcm.model.JsonResponse;
import com.xcm.model.TbDeviceUpgrade;
import com.xcm.model.dto.DeviceGroupListDTO;
import com.xcm.model.dto.DeviceModelDTO;
import com.xcm.model.vo.DeviceInfoListVO;
import com.xcm.model.vo.FirmWareListVO;
import com.xcm.model.vo.FirmWareVO;
import com.xcm.page.PageInfo;
import com.xcm.service.DeviceGroupService;
import com.xcm.service.DeviceInfoService;
import com.xcm.service.DeviceModelService;
import com.xcm.service.FirmWareService;
import com.xcm.util.GetUserUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @ClassName FirmWareController
 * @Description 固件管理控制类
 * @Author HanQinrui
 * @Date 2018/5/7 9:42
 * @Version 1.0
 **/
@Controller
@RequestMapping(value = "/firmWare")
public class FirmWareController {
    private static Logger logger = LoggerFactory.getLogger(FirmWareController.class);
    @Autowired
    private FirmWareService firmWareService;
    @Autowired
    private DeviceModelService deviceModelService;
    @Autowired
    private DeviceGroupService deviceGroupService;
    @Autowired
    private RedisCacheDao redisCacheDao;
    @Autowired
    private CustomProperties customProperties;
    @Autowired
    private DeviceInfoService deviceInfoService;
    /**
     * 固件分页列表
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping(value = "/listByPage")
    public Object listByPage(Integer pageNum, Integer pageSize, Model model) {
        PageInfo<FirmWareListVO> pageIno = firmWareService.listByPage(pageNum, pageSize);
        model.addAttribute("pageNum", pageIno.getPageNum());
        model.addAttribute("pageSize", pageIno.getPageSize());
        model.addAttribute("total", pageIno.getTotal());
        model.addAttribute("resultList", pageIno.getList());
        return "firmware-list";
    }

    /**
     * 跳转更新固件
     * @param hardVersion 固件版本号
     * @param deviceStatus 在线状态 0.在线; 1.离线
     * @param deviceModel 机型
     * @param groupCode 分组编码
     * @param province 省
     * @param city 市
     * @param area 区
     * @param deviceUpgradeId 固件ID
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping(value = "/updateFirmWareForward")
    public Object updateFirmWareForward(String hardVersion, String deviceStatus, String deviceModel, String groupCode,
                                        String province,String city, String area, String deviceUpgradeId,
                                        Integer pageNum, Integer pageSize, Model model) {
        if(StringUtils.isBlank(deviceUpgradeId)) {
            model.addAttribute("errorCode",ResponseConstant.CODE_FAIL);
            model.addAttribute("errorMsg",ResponseConstant.MSG_PARAM_ERROR);
            return "firmware_upgrade";
        }

        // 根据固件Id查询固件名称和版本号
        FirmWareListVO firmWareVO = firmWareService.getFirmWareByDeviceUpgradeId(deviceUpgradeId);
        if(firmWareVO == null) {
            model.addAttribute("errorCode",ResponseConstant.CODE_FAIL);
            model.addAttribute("errorMsg",ResponseConstant.MSG_PARAM_ERROR);
            return "firmware_upgrade";
        }

        // 查询所有固件版本号
        List<String> versionCodeList = deviceInfoService.listAllFirmwareVersionCode();
        model.addAttribute("versionCodeList",versionCodeList);
        //在线状态
        Map<Object, Object> deviceStatusMap = Maps.newHashMap();
        deviceStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_ON_LINE, "在线");
        deviceStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE, "离线");
        model.addAttribute("deviceStatusMap", deviceStatusMap);
        //机型
        List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModelsSelectedOfFirmware(Long.parseLong(deviceUpgradeId));
        model.addAttribute("deviceModelList", deviceModelList);
        //分组
        List<DeviceGroupListDTO> deviceGroupList = deviceGroupService.listAllDeviceGroup();
        model.addAttribute("deviceGroupList", deviceGroupList);
        //在线终端总数
        Long onlineCount = firmWareService.getFirmWareDeviceOnlineCount(hardVersion,deviceModel, groupCode, province, city, area);
        model.addAttribute("onlineCount", onlineCount);
        //离线终端总数
        Long offlineCount = firmWareService.getFirmWareDeviceOfflineCount(hardVersion, deviceModel, groupCode, province, city, area);
        model.addAttribute("offlineCount",offlineCount);

        // 查询终端列表信息
        PageInfo<DeviceInfoListVO> pageIno = firmWareService.updateFirmWareListByPage(
                hardVersion, deviceStatus, deviceModel, groupCode,
                province, city, area, deviceUpgradeId, pageNum, pageSize);
        model.addAttribute("pageNum", pageIno.getPageNum());
        model.addAttribute("pageSize", pageIno.getPageSize());
        model.addAttribute("total", pageIno.getTotal());
        model.addAttribute("resultList", pageIno.getList());
        model.addAttribute("errorCode",ResponseConstant.CODE_SUCCESS);
        // 查询条件回显
        // 终端当前固件版本

        model.addAttribute("hardVersion",hardVersion == "" ? null : hardVersion);
        // 终端在线状态
        model.addAttribute("deviceStatus",deviceStatus == "" ? null : deviceStatus);
        // 终端机型
        model.addAttribute("deviceModel",deviceModel == "" ? null : deviceModel);
        // 分组编码
        model.addAttribute("groupCode",groupCode == "" ? null : groupCode);
        // 省
        model.addAttribute("province",province);
        // 市
        model.addAttribute("city",city);
        // 区
        model.addAttribute("area",area);
        // 固件Id
        model.addAttribute("deviceUpgradeId",deviceUpgradeId);
        // 固件名称
        model.addAttribute("firmWareName",firmWareVO.getName());
        // 固件版本号
        model.addAttribute("firmWareVersionCode",firmWareVO.getVersionCode());
        return "firmware_upgrade";
    }
    /**
     * 更新终端的固件升级Id
     * @param deviceInfoIds 终端Id(多个Id之间用逗号隔开)
     * @param deviceUpgradeId 固件Id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateFirmWare")
    public Object updateFirmWareAjax(String deviceInfoIds, Integer deviceUpgradeId, HttpServletRequest request) {
        //获取用户信息
        JSONObject user = null;
        try {
            user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
        } catch (ServiceException e) {
            e.printStackTrace();
            logger.error("FirmWareController firmware_upgrade 更新固件：" + e.getMessage());
            return e.getMessage();
        }
        if(user == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名为空，请联系管理员");
        }
        // 更新成功条数
        int successCount = 0;
        if (StringUtils.isBlank(deviceInfoIds)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL,"更新完成！成功0，失败100！请选择终端！");
        }
        if (deviceUpgradeId == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL,"更新完成！成功0，失败100！升级ID为空，请联系管理员");
        }
        try {
            successCount = firmWareService.updateFirmWareUpgradeIdByDeviceInfoIds(deviceInfoIds, deviceUpgradeId, user, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FirmWareController firmware_upgrade 更新固件：" + e.getMessage());
            return e;
        }
        // 更新失败条数
        int failCount = deviceInfoIds.split(",").length;
        failCount = failCount - successCount;
        return new JsonResponse(ResponseConstant.CODE_SUCCESS, "更新完成！成功" + successCount + "，失败" + failCount + "！");
    }

    /**
     * 跳转到添加固件页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/addFirmwareForward")
    public String addFirmwareForward(Model model) {
        List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModels();
        model.addAttribute("deviceModelList", deviceModelList);
        return "firmware-add";
    }

    /**
     * 保存固件升级信息
     */
    @ResponseBody
    @RequestMapping(value = "/saveFirmWare")
    public Object saveFirmWare(TbDeviceUpgrade deviceUpgrade, HttpServletRequest request) {
        //获取用户信息
        JSONObject user = null;
        try {
            user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
        } catch (ServiceException e) {
            e.printStackTrace();
            logger.error("FirmWareController saveFirmWare 保存固件升级信息失败：" + e.getMessage());
            return new JsonResponse(ResponseConstant.CODE_FAIL,"保存固件升级信息失败");
        }
        if(user == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名为空，请联系管理员");
        }
        //验证参数
        if (deviceUpgrade == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
        }
        //验证参数
        if (StringUtils.isBlank(deviceUpgrade.getName()) || StringUtils.isBlank(deviceUpgrade.getModel())
                || StringUtils.isBlank(deviceUpgrade.getSize()) || deviceUpgrade.getVersionName() == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
        }
        try {
            int row = firmWareService.saveFirmware(deviceUpgrade, user, request);
            if (row == -1) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, "固件名称不能重复");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FirmWareController saveFirmWare 保存固件升级信息失败：" + e.getMessage());
            return new ControllerException("保存固件升级信息失败");
        }
        return "保存固件成功";
    }

    /**
     * 检查终端是否重复升级
     * @param deviceInfoIds 终端Id(多个Id之间用逗号隔开)
     * @param deviceUpgradeId 固件Id
     * @param firmWareName 所选固件名称
     * @param firmWareVersionCode 所选固件版本号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkRepeat")
    public Object checkRepeatAjax(String deviceInfoIds, Long deviceUpgradeId, String firmWareName, String firmWareVersionCode) {
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isBlank(deviceInfoIds) ) {
            return new ControllerException("更新失败，请选择终端！");
        }
        if (deviceUpgradeId == null) {
            return new ControllerException("升级ID为空，请联系管理员！");
        }
        try {
            resultMap = firmWareService.checkRepeat(deviceInfoIds, deviceUpgradeId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FirmWareController firmware_upgrade 更新固件失败：" + e.getMessage());
            return new ControllerException("更新固件失败");
        }

        // 重复升级的终端Id，多个Id之间用逗号隔开
        String repeatDeviceIds = resultMap.get("repeatDeviceInfoIds").toString();
        if(StringUtils.isNotBlank(repeatDeviceIds)) {
            repeatDeviceIds = repeatDeviceIds.substring(0, repeatDeviceIds.length() - 1);
        }

        // 可以更新的终端Id,多个Id之间用逗号隔开
        String unRepeatDeviceIds = resultMap.get("unRepeatDeviceInfoIds").toString();
        if(StringUtils.isNotBlank(unRepeatDeviceIds)) {
            unRepeatDeviceIds = unRepeatDeviceIds.substring(0,unRepeatDeviceIds.length() - 1);
        }

        if(StringUtils.isBlank(repeatDeviceIds)) {
            // 没有固件版本重复的终端,即所选终端全部可更新
            return new JsonResponse(ResponseConstant.CODE_SUCCESS, unRepeatDeviceIds,
                    "确认是否更新 "+firmWareName+" 固件版本号：" + firmWareVersionCode);
        } else if(StringUtils.isBlank(unRepeatDeviceIds)){
            // 没有可以更新的终端
            return new JsonResponse(ResponseConstant.CODE_FAIL,
                    "所选终端设备固件版本重复，请重新选择");
        } else {
            // 有可以更新的终端
            return new JsonResponse(ResponseConstant.CODE_SUCCESS, unRepeatDeviceIds,
                    "终端设备 " + repeatDeviceIds + "版本重复! 其余终端设备是否更新 " + firmWareName + " 固件版本号：" + firmWareVersionCode);
        }

    }

    /**
     * 跳转到升级固件页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/promoteFirmwareForward")
    public String promoteFirmwareForward(Long deviceUpgradeId, Model model) {
        List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModels();
        try {
            FirmWareListVO firmWareListVO = firmWareService.getFirmWareByDeviceUpgradeId(deviceUpgradeId.toString());
            FirmWareVO firmWareVO = new FirmWareVO();
            BeanUtils.copyProperties(firmWareListVO, firmWareVO);
            firmWareVO.setModel(Arrays.asList(firmWareListVO.getModel().split(",")));
            model.addAttribute("deviceModelList", deviceModelList);
            model.addAttribute("firmWareListVO", firmWareVO);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FirmWareController promoteFirmwareForward 跳转到升级固件页面：" + e.getMessage());
        }
        return "firmware-promote";
    }

    /**
     * 升级固件
     */
    @ResponseBody
    @RequestMapping(value = "/promoteFirmWare")
    public Object promoteFirmWare(TbDeviceUpgrade deviceUpgrade, HttpServletRequest request) {
        //获取用户信息
        JSONObject user = null;
        try {
            user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
        } catch (ServiceException e) {
            e.printStackTrace();
            logger.error("FirmWareController promoteFirmWare 升级固件失败：" + e.getMessage());
            return new JsonResponse(ResponseConstant.CODE_FAIL, "升级固件失败");
        }
        if(user == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名为空，请联系管理员");
        }
        if (deviceUpgrade == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
        }
        if (deviceUpgrade.getDeviceUpgradeId() == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "固件ID不能为空");
        }
        if (StringUtils.isBlank(deviceUpgrade.getUrl())) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "请上传固件");
        }
        if (StringUtils.isBlank(deviceUpgrade.getName())) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "固件名称不能为空");
        }
        if (StringUtils.isBlank(deviceUpgrade.getVersionName())) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "固件版本号不能为空");
        }
        if (StringUtils.isBlank(deviceUpgrade.getModel())) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, "机型不能为空");
        }
        try {
            FirmWareListVO old = firmWareService.getFirmWareByDeviceUpgradeId(String.valueOf(deviceUpgrade.getDeviceUpgradeId()));
            if (null == old) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, "固件不存在");
            }
            if (!old.getName().equals(deviceUpgrade.getName())) {
                int count = firmWareService.countByParams(deviceUpgrade);
                if (count > 0) {
                    return new JsonResponse(ResponseConstant.CODE_FAIL, "固件名称已存在，请重新填写");
                }
            }
            firmWareService.promoteFirmWare(deviceUpgrade, user, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FirmWareController promoteFirmWare 升级固件失败：" + e.getMessage());
            return new JsonResponse(ResponseConstant.CODE_FAIL, "升级固件失败");
        }
        return "升级固件成功";
    }
}
